<template>
  <div class="form-main">
    <div class="form-tit" v-if="isTemp">
      <el-form
        :inline="true"
        :model="formdata"
        class="ky-form-inline ky-form-inline-sm">
        <el-form-item label="模板名称：">
          <el-input v-model="formdata.recordCode" placeholder="请输入" style="width: 220px;"></el-input>
        </el-form-item>
      </el-form>
    </div>

    <div class="form-grid">
      <div class="fg-tit"><div class="txt">预约渠道管理</div></div>
      <div class="fg-main">
        <el-form
          :inline="true"
          :model="formdata"
          label-position="top"
          class="ky-form-inline ky-form-inline-sm ruleTemp-channel-form">
          <el-form-item label="外院预约">
            <el-select v-model="channel.WYYY.value" placeholder="请选择" multiple clearable>
              <el-option
                v-for="item in channel.WYYY.options"
                :key="item"
                :label="item"
                :value="item">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="临床预约">
            <el-select v-model="channel.LCYY.value" placeholder="请选择" multiple clearable>
              <el-option
                v-for="item in channel.LCYY.options"
                :key="item"
                :label="item"
                :value="item">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="转诊预约">
            <el-select v-model="channel.VIP.value" placeholder="请选择" multiple clearable>
              <el-option
                v-for="item in channel.VIP.options"
                :key="item"
                :label="item"
                :value="item">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
    </div>

    <div class="form-grid">
      <div class="fg-tit">
        <div class="txt">过滤条件</div>
        <div class="flr-add" @click="addCondition"><i class="el-icon-circle-plus-outline"></i> 添加条件</div>
      </div>
      <div class="fg-main flr-main">
        <div
          class="rule-item"
          v-for="(item, index) in formdata.appointmentFilters"
          :key="index"
        >
          <el-select
            style="width: 154px"
            size="small"
            v-model="item.parametersType"
            placeholder="请选择过滤条件"
            clearable
            @change="changeCondition(item, index)"
          >
            <el-option
              v-for="_item in ruleConditionOptionsFlr"
              :key="_item.dicEname"
              :label="_item.dicName"
              :value="_item.dicEname"
            ></el-option>
          </el-select>
          <el-input-number
            style="width: 175px"
            size="small"
            v-model="item.parametersValues"
            v-if="item.conditionControl === '1'"
          ></el-input-number>
          <el-input
            v-else-if="item.conditionControl === '2'"
            style="width: 175px"
            class="inline-input"
            size="small"
            v-model="item.parametersValues"
            :placeholder="`请输入${placeholderKey[index]||' '}`"
            clearable
          ></el-input>
          <el-select
            style="width: 175px"
            size="small"
            v-model="item.parametersValues"
            v-else-if="item.conditionControl === '3'"
            :placeholder="`请选择${placeholderKey[index] ||' '}`"
            clearable
          >
            <el-option
              v-for="(
                _item, _index
              ) in item.conditionSelectValueOptions"
              :key="_index"
              :label="_item"
              :value="_item"
            ></el-option>
          </el-select>
          <el-select
            style="width: 175px"
            size="small"
            multiple
            v-model="item.parametersValues"
            v-else-if="item.conditionControl === '5'"
            :placeholder="`请选择${placeholderKey[index] ||' '}`"
            clearable
          >
            <el-option
              v-for="(
                _item, _index
              ) in item.conditionSelectValueOptions"
              :key="_index"
              :label="_item"
              :value="_item"
            ></el-option>
          </el-select>
          <el-date-picker
            size="small"
            v-else-if="item.conditionControl === '4'"
            style="width: 175px"
            v-model="item.parametersValues"
            type="date"
            placeholder="选择日期时间"
          >
          </el-date-picker>
          <el-input v-else style="width:175px" class="inline-input" size="small" v-model="item.parametersValues" :placeholder="`请输入${placeholderKey[index] ||' '}`" clearable></el-input>
          <i
            class="el-icon-error"
            @click="deleteCondition(index)"
            v-if="formdata.appointmentFilters.length != 1"
          ></i>
        </div>
      </div>
    </div>

    <div class="form-grid">
      <div class="fg-tit"><div class="txt">可用检查部位</div></div>
      <div class="fg-main table-main" v-loading="treeloading">
        <el-form
          ref="formdata"
          :inline="true"
          :model="formdata"
          class="ky-form-inline ky-form-inline-sm">
          <el-form-item>
            <el-input prefix-icon="el-icon-search" v-model="filterText" size="small" placeholder="请输入内容"></el-input>
          </el-form-item>
          <el-form-item class="inline-block tree" prop="ruleTypes">
            <el-tree
              ref="tree"
              :data="checkTypeData"
              show-checkbox
              node-key="id"
              @check="handleCheckChange"
              :auto-expand-parent="false"
              :props="defaultProps"
              :filter-node-method="filterNode">
            </el-tree>
          </el-form-item>
        </el-form>
      </div>
    </div>

  </div>
</template>

<script>
import {
  getItemDicList
} from '@/api/api'
import { getBigPartGettreeRoom } from '@/api/room'
import { Options } from '@/utils/constant'
let channelSplitKey = '、'
export default {
  props: {
    hospitalCode: {
      type: String,
      default: ''
    },
    dep: {
      type: String,
      default: ''
    },
    isTemp: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      parametersValuesSplit: this.$store.state.user.parametersValuesSplit || channelSplitKey,
      options: Options,
      formdata: {
        recordCode: '', // 模板名称
        appointmentFilters: []
      },
      ruleConditionOptionsFlr: [],
      ruleConditionOptions: [], // 规则数据字典
      checkedPartNodes: [], // 选中的检查部位
      // 预约渠道
      channel: {
        WYYY: {
          value: [],
          label: '外院预约',
          options: Options.channelOptions.WYYY
        },
        LCYY: {
          value: [],
          label: '临床预约',
          options: Options.channelOptions.LCYY
        },
        VIP: {
          value: [],
          label: '转诊预约',
          options: Options.channelOptions.VIP
        }
      },
      // 检查项目
      treeloading: false,
      checkTypeData: [],
      filterText: '',
      defaultProps: {
        children: 'childrens',
        label: 'text'
      },
      placeholderKey: [] // 记录切换控件显示的默认提醒
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree && this.$refs.tree.filter(val)
    },
    hospitalCode(val) {
      if (this.dep && val) {
        this.checkTypeData = []
        this.getBigPartGettreeList()
      }
    },
    dep(val) {
      if (this.hospitalCode && val) {
        this.checkTypeData = []
        this.getBigPartGettreeList()
      }
    }
  },
  mounted() {
    this.init()
  },
  methods: {
    async init(data) {
      await this.getRuleItemDicList()
      if (this.hospitalCode && this.dep) {
        await this.getBigPartGettreeList()
      }
      this.channel['WYYY'].value = []
      this.channel['LCYY'].value = []
      this.channel['VIP'].value = []
      this.formdata.appointmentFilters = data ? JSON.parse(JSON.stringify(data.appointmentFilters)) : []
      this.formdata.recordCode = data ? this.isTemp ? data.recordCode : data.remark1 : ''
      this.$refs.tree && this.$refs.tree.setCheckedKeys([])
      this.calSetRule()
    },
    getRuleData() {
      return new Promise(async resolve => {
        const resFlr = JSON.parse(JSON.stringify(this.formdata))
        // 判断数据格式
        for (let i = 0; i < resFlr.appointmentFilters.length; i++) {
          // 如果只有一组空数据，直接跳过
          if (!resFlr.appointmentFilters[i].parametersType && !resFlr.appointmentFilters[i].parametersValues) {
            resFlr.appointmentFilters.splice(i, 1)
            continue
          }
          if (resFlr.appointmentFilters[i].parametersValues && typeof resFlr.appointmentFilters[i].parametersValues === 'object') {
            resFlr.appointmentFilters[i].parametersValues = resFlr.appointmentFilters[i].parametersValues.join(channelSplitKey)
          } else if (typeof resFlr.appointmentFilters[i].parametersValues === 'number') {
            // 直接改格式，改了以后 下面会重新变回原来的格式
            if (resFlr.appointmentFilters[i].parametersValues < 0) {
              this.$message.warning(`${resFlr.appointmentFilters[i].parametersName} 不能小于0`)
              return false
            }
            let copyData = {
              parametersName: resFlr.appointmentFilters[i].parametersName,
              parametersType: resFlr.appointmentFilters[i].parametersType,
              parametersValues: resFlr.appointmentFilters[i].parametersValues.toString()
            }
            delete resFlr.appointmentFilters[i]
            resFlr.appointmentFilters[i] = copyData
          }
          if (!resFlr.appointmentFilters[i].parametersValues && resFlr.appointmentFilters[i].parametersType) {
            this.$message.warning('请完整输入参数列表数据')
            return
          }
        }
        const _appoFlr = await this.getTreePartChecked()
        if (_appoFlr && _appoFlr.length > 0) {
          const _appoFlrObj = {
            parametersType: this.$store.state.user.parametersTypeByPartKey2,
            parametersValues: _appoFlr.join(this.parametersValuesSplit),
            parametersName: '检查部位'
          }
          resFlr.appointmentFilters.push(_appoFlrObj)
        }

        // 预约渠道获取
        for (let k in this.channel) {
          if (this.channel[k].value.length > 0) {
            const _appoFlrObj = {
              parametersType: k,
              parametersValues: this.channel[k].value.join(parametersValuesSplit),
              parametersName: this.channel[k].label
            }
            resFlr.appointmentFilters.push(_appoFlrObj)
          }
        }
        // 判断是否为快速选择模板参数模板数据
        resFlr.recordCode = this.isTemp ? this.formdata.recordCode : resFlr.recordCode
        resolve(JSON.stringify(resFlr))
      })
    },
    calSetRule() {
      const appoFlr = JSON.parse(JSON.stringify(this.formdata.appointmentFilters))
      this.formdata.appointmentFilters = []
      if (appoFlr.length === 0) {
        this.addCondition()
      }
      for (let index = 0; index < appoFlr.length; index++) {
        let flrObj = appoFlr[index]
        if (flrObj.parametersType === this.$store.state.user.parametersTypeByPartKey2) {
          // 检测项目（大检查项目）
          this.checkedPartNodes = flrObj.parametersValues ? flrObj.parametersValues.split(this.parametersValuesSplit) : [] // .map(item => {return {name: item}})
          this.setCheckedPartIds()
          continue
        }
        if (flrObj.parametersType === 'WYYY' || flrObj.parametersType === 'LCYY' || flrObj.parametersType === 'VIP') {
          // 外院预约、临床预约、转诊预约
          this.channel[flrObj.parametersType].value = flrObj.parametersValues ? flrObj.parametersValues.split(channelSplitKey) : []
          continue
        }
        let filters = {
          parametersType: flrObj.parametersType,
          parametersValues: flrObj.parametersValues,
          parametersName: flrObj.remark1,
          conditionControl: '',
          conditionSelectValueOptions: []
        }
        this.formdata.appointmentFilters.push(filters)
        const appoFlrLen = this.formdata.appointmentFilters.length
        this.changeCondition(this.formdata.appointmentFilters000[appoFlrLen - 1], appoFlrLen - 1, 'init')
      }
      if (this.formdata.appointmentFilters.length === 0) {
        this.addCondition()
      }
    },

    // 添加场景条件
    addCondition() {
      this.formdata.appointmentFilters.push({
        parametersType: '',
        parametersValues: '',
        parametersName: '',
        conditionControl: '',
        conditionSelectValueOptions: []
      })
    },
    // 删除场景条件
    deleteCondition(index) {
      if (this.formdata.appointmentFilters.length === 1) {
        this.$message.warning('当前只有一个条件')
        return
      }
      this.formdata.appointmentFilters.splice(index, 1)
    },
    changeCondition(_item, _index, showParams) {
      // 如果是读数据展示在form上的 不用清空数据；否则每次切换改变的时候 都需要清空数据
      if (!showParams) {
        this.formdata.appointmentFilters[_index].parametersValues = ''
      }
      this.getControlAndValue(_item, _index)
    },
    async getControlAndValue(_item, _index) {
      // 找remark 判断控件
      // index 是 _item在规则数据字典中的位置
      let index = this.ruleConditionOptions.findIndex(
        (item) => item.dicEname === _item.parametersType
      )
      // 规则数据字典存在
      if (index !== -1) {
        this.placeholderKey[_index] = this.ruleConditionOptions[index].dicName
        this.formdata.appointmentFilters[_index].parametersName = this.ruleConditionOptions[index].dicName
        // 存在conditionValue、是字符串、多选择的控件array，需要进行convert '1,2'=>[1,2]
        // 给编辑的时候使用
        if (
          this.ruleConditionOptions[index].controllType === '5' &&
          _item.parametersValues &&
          typeof _item.parametersValues === 'string'
        ) {
          this.formdata.appointmentFilters[
            _index
          ].parametersValues = this.formdata.appointmentFilters[
            _index
          ].parametersValues.split(this.parametersValuesSplit)
        }
        if (
          this.ruleConditionOptions[index].controllType === '1' &&
          _item.parametersValues &&
          typeof _item.parametersValues === 'number'
        ) {
          this.formdata.appointmentFilters[
            _index
          ].parametersValues = this.formdata.appointmentFilters[
            _index
          ].parametersValues.toString()
        }
        // 获取相应控件
        this.formdata.appointmentFilters[
          _index
        ].conditionControl = this.ruleConditionOptions[index].controllType
        // this.formdata.appointmentFilters[_index].modelType = this.ruleConditionOptions[index].modelType
        // 获取相应的方法 来获取控件里面的数值
        if (this.ruleConditionOptions[index].clientMethod) {
          // 获取方法名字 例如 getDepArea
          await this[this.ruleConditionOptions[index].clientMethod](_index)
        } else {
          console.log('不存在相应方法')
        }
      }
    },
    // 获取过滤条件类型
    getRuleItemDicList() {
      return new Promise(async resolve => {
        if (this.ruleConditionOptionsFlr.length) {
          resolve()
        } else {
          const params = {
            HospitalCode: this.hospitalCode
          }
          await getItemDicList(params).then(res => {
            if (res && res.code === 10000) {
              this.ruleConditionOptions = res.content.list.filter(item => item.modelType === 2)
              this.ruleConditionOptionsFlr = this.ruleConditionOptions.filter(item => {
                // this.$store.state.user.parametersTypeByPartKey2 =  dengjipart
                return (
                  item.dicEname !== this.$store.state.user.parametersTypeByPartKey2 &&
                  item.dicEname !== 'CheckClass' &&
                  item.dicEname !== 'CheckRoom' &&
                  item.dicEname !== 'Modality' &&
                  item.dicEname !== 'DepArea' &&
                  item.dicEname !== 'checkDep' &&
                  item.dicEname !== 'Dep' &&
                  item.dicEname !== 'VIP' &&
                  item.dicEname !== 'WYYY' &&
                  item.dicEname !== 'LCYY'
                )
              })
            }
          })
          resolve()
        }
      })
    },
    getSex(_index) {
      this.formdata.appointmentFilters[_index].conditionSelectValueOptions = ['男', '女', '其他']
    },
    getPatType(_index) {
      this.formdata.appointmentFilters[_index].conditionSelectValueOptions = this.options.patientTypeItemOptions.map(item => item.label)
    },
    getWeek(_index) {
      this.formdata.appointmentFilters[_index].conditionSelectValueOptions = this.options.weekOptions
    },
    // 默认类型 不用判断
    getDefault(_index) {
      this.formdata.appointmentFilters[_index].conditionSelectValueOptions = []
    },
    getYN(_index) {
      this.formdata.appointmentFilters[_index].conditionSelectValueOptions = ['是', '否']
    },
    getExamMethod(_index) {
      this.formdata.appointmentFilters[_index].conditionSelectValueOptions = ['平扫', '增强']
    },
    // 检查部位的已选择数据
    setCheckedPartIds() {
      // 获取部位对应id
      let checkedId = []
      const findIdFun = (arr, text) => {
        const arrLen = arr.length
        for (let i = 0; i < arrLen; i++) {
          if (arr[i].childrens && arr[i].childrens.length > 0) {
            findIdFun(arr[i].childrens, text)
          } else {
            if (arr[i].text === text) {
              checkedId.push(arr[i].id)
            }
          }
        }
      }
      this.checkedPartNodes.forEach(part => {
        findIdFun(this.checkTypeData, part)
      })
      // console.log(checkedId)
      this.$refs.tree && this.$refs.tree.setCheckedKeys(checkedId)
    },
    // 监听检查项目的树选择
    handleCheckChange(nodeData, checkedData) {
      this.getTreeCheckedData('tree')
    },
    // 获取检查项目，检查部位、检查项目
    getBigPartGettreeList() {
      return new Promise(async resolve => {
        if (this.checkTypeData.length !== 0 && this.treeloading) {
          resolve()
          return
        }
        const params = {
          HospitalCode: this.hospitalCode,
          Dep: this.dep
        }
        this.treeloading = true
        await getBigPartGettreeRoom(params).then(res => {
          this.treeloading = false
          if (res && res.code === 10000) {
            let partNodes = JSON.parse(JSON.stringify(res.content.childrens))
            // partNodes.forEach(item => {
            //   item.childrens = []
            // })
            this.checkTypeData = partNodes
            // console.log(this.checkTypeData)
          }
        })
        resolve()
      })
    },
    // 获取树的选中对象数组
    getTreeCheckedData(treeModel) {
      let checkedNodes = this.$refs[treeModel].getCheckedNodes()
      // console.log(checkedNodes)
      return checkedNodes
    },
    // 获取检查部位的选中数据 [text,text]
    getTreePartChecked() {
      const _ckdNode = this.getTreeCheckedData('tree')
      const ckdLen = _ckdNode.length
      return new Promise(resolve => {
        let ckdArr = []
        if (ckdLen === 0) {
          resolve(ckdArr)
          return
        }
        _ckdNode.forEach(item => {
          if (item.level === 2) {
            ckdArr.push(item.text)
          }
        })
        resolve(ckdArr)
      })
    },
    filterNode(value, data, node) {
      if (!value) {
        node ? node.expanded = false : null
        return true
      }
      if (typeof value === 'string') {
        let flag = false
        if (data.text.indexOf(value) !== -1) {
          flag = true
        }
        return flag
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.form-grid{
  padding-bottom:10px;
  border-bottom: solid 1px #DBDFE9;
  &:last-child{
    border-bottom: none;
  }
  .fg-tit{
    display: flex;
    line-height: 44px;
    .txt{
      flex: 1;
      font-weight: bold;
    }
    .flr-add{
      user-select: none;
      color: #00C0EF;
      cursor: pointer;
    }
  }
}
.flr-main{
  .rule-item{
    margin-bottom: 4px;
  }
}
.table-main{
  padding: 8px 10px;
  background-color: #F3F6FB;
  /deep/ .el-table td,/deep/  .el-table th{
    padding: 4px 0;
  }
}
.tree{
  max-height: 280px;
  overflow: auto;
  width: 100%;
  /deep/ .el-form-item__content{
      display: block;
      .el-tree{
          height:100%
      }
  }
}
.ruleTemp-channel-form{
  /deep/ .el-select {
    width: 126px;
  }
  /deep/ .el-form-item{
    margin-right: 6px;
    font-weight: 500;
    &:last-child{
      margin-right: 0;
    }
  }
  /deep/ .el-form-item .el-form-item__label {
    line-height: 18px;
  }
}
</style>
